package cc.magicjson.synthesis.chain;


import cc.magicjson.synthesis.context.DiscountContext;
import cc.magicjson.synthesis.model.Order;

import java.math.BigDecimal;

/**
 * 最终金额检查器，确保最终金额不小于0，并做最后的金额校验
 */
public class FinalAmountChecker extends DiscountChecker {

    private static final String ORIGINAL_FINAL_AMOUNT_KEY = "ORIGINAL_FINAL_AMOUNT";

    @Override
    protected boolean doCheck(DiscountContext context) {
        Order order = context.getOrder();

        // 保存原始最终金额，用于回滚
        context.setAttribute(ORIGINAL_FINAL_AMOUNT_KEY, order.getFinalAmount());

        // 确保最终金额不小于0
        if (order.getFinalAmount().compareTo(BigDecimal.ZERO) < 0) {
            order.setFinalAmount(BigDecimal.ZERO);
        }

        // 确保折扣金额不超过原始金额
        BigDecimal originalAmount = order.getOriginalAmount();
        BigDecimal discountAmount = order.getDiscountAmount();

        if (discountAmount.compareTo(originalAmount) > 0) {
            order.setDiscountAmount(originalAmount);
            order.setFinalAmount(BigDecimal.ZERO);
        }

        return true; // 继续处理链
    }

    @Override
    protected void doRollback(DiscountContext context) {
        // 恢复原始最终金额
        BigDecimal originalFinalAmount = context.getAttribute(ORIGINAL_FINAL_AMOUNT_KEY);
        if (originalFinalAmount != null) {
            Order order = context.getOrder();
            order.setFinalAmount(originalFinalAmount);
        }
    }
}
